#include <stdio.h>

#include <SDL2/SDL.h>
#include "res.h"
#include "playerAnim.h"

#define FRAMERATE 60
#define WINDOW_W 600
#define WINDOW_H 480
#define MARGIN 50


SDL_Window *window;
SDL_Renderer *render;
SDL_Event e;
int gQuit = 0;
DisplayObject *anim;
TEXT_TEXTURE txtText1;
TTF_Font *font;

int init()
{
  int ret = 1;
 
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0)
  {
    printf("sdl could not init!sdl error:%s\n", SDL_GetError());
    ret = 0;
  }
  else
  {
    if ((window = SDL_CreateWindow("sdl", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 400, 300, 0)) == NULL)
    {
      printf("could not create! error:%s\n", SDL_GetError());
      ret = 0;
    }
    else
    {
      if ((render = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == NULL)
      {
        printf("render could not create! error:%s\n", SDL_GetError());
        ret = 0;
      }
    }
  }
  return ret;
}

void handleButtons()
{
  switch (e.type)
  {
  case SDL_QUIT:
    gQuit = 1;
    break;
  case SDL_KEYDOWN:
  {
    int mkey = e.key.keysym.sym;
    if (mkey == 'q')
      gQuit = 1;
    else if (mkey == 'a')
    {
      walkAnimDir(anim, 3);
    }
    else if (mkey == 'w')
    {
      walkAnimDir(anim, 1);
    }
    else if (mkey == 's')
    {
       walkAnimDir(anim, 0);
    }
    else if (mkey == 'd')
    {
      walkAnimDir(anim, 2);
    }
    break;
  }
  case SDL_KEYUP:
    WalAnimationStop(anim);
    break;
  }
}
void draw()
{
  SDL_SetRenderDrawColor(render, 255, 255, 255, 255);
  SDL_RenderClear(render);
SDL_RenderSetScale(render,2.0f, 2.0f);
  DisplayObjectDraw(anim, render);
  setTextTexture(render, &txtText1, font, "你好SDL");
  txtText1.txtDstRect.x = MARGIN;
  txtText1.txtDstRect.y = MARGIN;
  SDL_RenderCopy(render, txtText1.txtText, NULL, &txtText1.txtDstRect);
  SDL_RenderPresent(render);
}
void tick()
{
  SDL_RenderClear(render);

  while (SDL_PollEvent(&e) != 0)
  {
    handleButtons();
  }
draw();
}

void loop()
{
  while (!gQuit)
  {
    uint32_t begin = SDL_GetTicks();
    tick();
    long current = SDL_GetTicks();
    long cost = current - begin;
    long frame = 1000 / FRAMERATE;
    long delay = frame - cost;

    if (delay > 0)
    {
      SDL_Delay(delay);
    }
  }
}
void createComponents() {
    anim = WalkAnimationCreate();
    font = resGetFont();
}

void freeComponents() {
    WalkAnimationDestroy(anim);
}
int main(int argc, char *argv[])
{
  if (!init())
  {
    printf("init error!\n");
  }
  else
  {
    if (resLoad(render))
    {
      return 1;
    }
    createComponents();
     playMusic();
    loop();
    freeComponents();
    resUnLoad();
    SDL_DestroyRenderer(render);
    SDL_DestroyWindow(window);
  }
  return 0;
}